<?php

class DB
{

    public $handle = false;
    public $handle_master = false;
    public $server;
    public $user;
    public $pass;
    public $database;
    public $count = 0;
    public $result = 0;

    public function DB()
    {
        global $CORE;
        if (!isset($CORE['db_connection']))
        {
            $this->connect();
        }
    }

    public function connect()
    {
        global $CORE;
        global $g_dbhost;
        global $g_db_sql_mode;
        if (!isset($CORE['db_connection']))
        {
            if (isset($g_dbhost) && is_array($g_dbhost))
            {
                $this->server = $g_dbhost[0];
                $this->user = G_DBUSER;
                $this->pass = G_DBPASS;
                $this->database = G_DBDATABASE;
                $handle = mysql_connect($this->server, $this->user, $this->pass);
                mysql_query($g_db_sql_mode);
                if ($handle == false)
                {
                    exit("连接 MASTER 资料库主机失败！" . mysql_error());
                }
                if (false == mysql_select_db($this->database, $handle))
                {
                    exit("连接 MASTER 资料库失败！" . mysql_error());
                }
                $CORE['db_connection_master'] = $handle;
                if (count($g_dbhost) == 1)
                {
                    $CORE['db_connection'] = $handle;
                }
                else
                {
                    $minhost = count($g_dbhost) < 3 ? 0 : 1;
                    $tries = 0;
                    $handle = false;
                    while ($tries < 10 && $handle == false)
                    {
                        $slave = rand($minhost, count($g_dbhost) - 1);
                        $handle = mysql_connect($g_dbhost[$slave], $this->user, $this->pass);
                        mysql_query($g_db_sql_mode);
                        ++$tries;
                    }
                    if ($handle == false)
                    {
                        exit("连接 SLAVE 资料库主机失败！" . mysql_error());
                    }
                    if (false == mysql_select_db($this->database, $handle))
                    {
                        exit("连接 SLAVE 资料库失败！" . mysql_error());
                    }
                    $CORE['db_connection'] = $handle;
                }
            }
            else
            {
                $this->server = G_DBSERVER;
                $this->user = G_DBUSER;
                $this->pass = G_DBPASS;
                $this->database = G_DBDATABASE;
                $handle = mysql_connect($this->server, $this->user, $this->pass);
                mysql_query($g_db_sql_mode);
                if ($handle == false)
                {
                    exit("连接资料库主机失败！" . mysql_error());
                }
                if (false == mysql_select_db($this->database, $handle))
                {
                    exit("连接资料库失败！" . mysql_error());
                }
                $CORE['db_connection'] = $handle;
                $CORE['db_connection_master'] = $handle;
            }
        }
        $this->handle = $CORE['db_connection'];
        $this->handle_master = $CORE['db_connection_master'];
        return $this->handle;
    }

    public function queryrow($sql)
    {
        $res = $this->query($sql);
        if (!$res)
        {
            return false;
        }
        $row = $this->fetch_row($res);
        $this->free_result($res);
        return $row;
    }

    public function getrs($sql)
    {
        $res = $this->query($sql);
        if (!$res)
        {
            return false;
        }
        $rows = array();
        while ($row = $this->fetch_object($res))
        {
            $rows[] = $row;
        }
        $this->free_result($res);
        return $rows;
    }

    public function getFieldsName($tblName)
    {
        $rows = array();
        if (!$this->connect())
        {
            return false;
        }
        $sql = "select * from " . $tblName . " LIMIT 0,1";
        $res = $this->query($sql);
        $fields = mysql_num_fields($res);
        $i = 0;
        while ($i < $fields)
        {
            $rows[] = mysql_field_name($res, $i);
            ++$i;
        }
        return $rows;
    }

    public function query($sql = "")
    {
        global $G_DB_QUERY_COUNT;
        global $CORE;
        global $g_cache;
        if (!$this->connect())
        {
            return false;
        }
        $time_begin = microtime(1);
        $this->sql = $sql;
        if (substr($sql, 0, 2) == "!!")
        {
            $handle = $this->handle_master;
            $sql = substr($sql, 2);
        }
        else
        {
            $handle = preg_match("/^select /i", $sql) ? $this->handle : $this->handle_master;
        }
        $res = mysql_query($sql, $handle);
        if (!$res)
        {
            $errCode = mysql_errno($handle);
            if (G_DEBUG)
            {
                $r = "<p>CODE(" . $errCode . "):" . mysql_error($handle) . "</p><p>SQL: " . $sql . "</p>";
                echo $r;
            }
            if ($errCode != 2006 && !preg_match("/^insert into dblog/i", $sql) && !preg_match("/^preg_match into k_sessions/i", $sql))
            {
                $buf = "CODE(" . $errCode . "):" . htmlspecialchars($sql, ENT_QUOTES);
                $this->query("insert into dblog (logs) values ('{$buf}')");
                if ($errCode == 1062 && ( eregi("^insert into bet ", $sql) || eregi("^insert into bet_", $sql) ) && isset($_SESSION['uid']) && 0 < ( $uid = intval($_SESSION['uid']) ))
                {
                    $this->query("DELETE FROM k_sessions WHERE uid=" . $uid);
                    unset($_SESSION['uid']);
                }
            }
        }
        $this->result = $res;
        ++$G_DB_QUERY_COUNT;
        $time_end = microtime(1);
        return $res;
    }

    public function num_rows($res = 0)
    {
        if (!$this->connect())
        {
            return false;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        return mysql_num_rows($res);
    }

    public function num_fields($res = 0)
    {
        if (!$this->connect())
        {
            return false;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        return mysql_num_fields($res);
    }

    public function fetch_field($res = 0)
    {
        if (!$this->connect())
        {
            return false;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        return mysql_fetch_field($res);
    }

    public function fetch_row($res = 0)
    {
        if (!$this->connect())
        {
            return false;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        return mysql_fetch_row($res);
    }

    public function fetch_array($res = 0)
    {
        if ($this->connect() == false)
        {
            return false;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        return @mysql_fetch_array($res);
    }

    public function fetch_object($res = 0)
    {
        if (!$this->connect())
        {
            return false;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        return mysql_fetch_object($res);
    }

    public function free_result($res = 0)
    {
        if (!$this->connect())
        {
            return false;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        return mysql_free_result($res);
    }

    public function data_seek($res, $count)
    {
        if (!$this->connect())
        {
            return false;
        }
        return @mysql_data_seek($res, $count);
    }

    public function backup($filename)
    {
        $crlf = "\r\n";
        $h = fopen($filename, "wb");
        fwrite($h, "# 备份日期：" . date("Y/m/d") . "{$crlf}");
        $rs = getdb("show tables");
        while (!$rs->eof)
        {
            $tbname = $rs->f[0];
            fwrite($h, "# Table：" . $tbname . "{$crlf}");
            $this->get_table_def($tbname, $h);
            $this->get_table_content($tbname, $h);
            $rs->movenext();
        }
        $rs->close();
        fclose($h);
    }

    public function Restore($filename)
    {
        $fp = fopen($filename, "rb");
        $str = "";
        while (!feof($fp))
        {
            $str .= fgets($fp, 1024);
        }
        $SQL = explode(";", $str);
        $i = 0;
        while ($i < count($SQL) - 1)
        {
            $this->unbuffered_query($SQL[$i]);
            ++$i;
        }
    }

    public function unbuffered_query($sql)
    {
        $handle = preg_match("/^select /i", $sql) ? $this->handle : $this->handle_master;
        if (!mysql_unbuffered_query($sql, $handle))
        {
            exit(mysql_error());
        }
    }

    public function get_table_def($table, $h)
    {
        $db = $this->database;
        $crlf = "\r\n";
        $schema_create = "";
        $schema_create .= "CREATE TABLE {$table} ({$crlf}";
        if (!( $result = mysql_db_query($db, "SHOW FIELDS FROM {$table}") ))
        {
            mysql_die();
        }
        while ($row = mysql_fetch_array($result))
        {
            $schema_create .= "   {$row['Field']} {$row['Type']}";
            if (isset($row['Default']) && (!empty($row['Default']) || $row['Default'] == "0" ))
            {
                $schema_create .= " DEFAULT '{$row['Default']}'";
            }
            if ($row['Null'] != "YES")
            {
                $schema_create .= " NOT NULL";
            }
            if ($row['Extra'] != "")
            {
                $schema_create .= " {$row['Extra']}";
            }
            $schema_create .= ",{$crlf}";
        }
        $schema_create = ereg_replace("," . $crlf . "\$", "", $schema_create);
        if (!( $result = mysql_db_query($db, "SHOW KEYS FROM {$table}") ))
        {
            mysql_die();
        }
        while ($row = mysql_fetch_array($result))
        {
            $kname = $row['Key_name'];
            if ($kname != "PRIMARY" && $row['Non_unique'] == 0)
            {
                $kname = "UNIQUE|{$kname}";
            }
            if (!isset($index[$kname]))
            {
                $index[$kname] = array();
            }
            $index[$kname][] = $row['Column_name'];
        }
        while (list( $x, $columns ) = x)
        {
            $schema_create .= ",{$crlf}";
            if ($x == "PRIMARY")
            {
                $schema_create .= "   PRIMARY KEY (" . implode($columns, ", ") . ")";
            }
            else if (substr($x, 0, 6) == "UNIQUE")
            {
                $schema_create .= "   UNIQUE " . substr($x, 7) . " (" . implode($columns, ", ") . ")";
            }
            else
            {
                $schema_create .= "   KEY {$x} (" . implode($columns, ", ") . ")";
            }
        }
        $schema_create .= "{$crlf})";
        fwrite($h, stripslashes($schema_create) . ";{$crlf}{$crlf}");
    }

    public function get_table_content($table, $h)
    {
        $db = $this->database;
        $crlf = "\r\n";
        if (!( $result = mysql_db_query($db, "SELECT * FROM {$table}") ))
        {
            
        }
        $i = 0;
        while ($row = mysql_fetch_row($result))
        {
            $table_list = "(";
            $j = 0;
            while ($j < mysql_num_fields($result))
            {
                $table_list .= mysql_field_name($result, $j) . ", ";
                ++$j;
            }
            $table_list = substr($table_list, 0, 0 - 2);
            $table_list .= ")";
            if (isset($GLOBALS['showcolumns']))
            {
                $schema_insert = "INSERT INTO {$table} {$table_list} VALUES (";
            }
            else
            {
                $schema_insert = "INSERT INTO {$table} VALUES (";
            }
            $j = 0;
            while ($j < mysql_num_fields($result))
            {
                if (!isset($row[$j]))
                {
                    $schema_insert .= " NULL,";
                }
                else if ($row[$j] != "")
                {
                    $schema_insert .= " '" . addslashes($row[$j]) . "',";
                }
                else
                {
                    $schema_insert .= " '',";
                }
                ++$j;
            }
            $schema_insert = ereg_replace(",\$", "", $schema_insert);
            $schema_insert .= ")";
            fwrite($h, trim($schema_insert) . ";{$crlf}");
            ++$i;
        }
    }

    public function table_exists($tablename, $res = 0)
    {
        return $this->is_table($tablename, $res);
    }

    public function is_table($tablename, $res = 0)
    {
        if (!$this->connect())
        {
            return FALSE;
        }
        if ($res == 0)
        {
            $res = $this->result;
        }
        $result = mysql_list_tables($this->database);
        if (!$result)
        {
            return FALSE;
        }
        while ($row = $this->fetch_array($result))
        {
            if ($tablename != $row[0])
            {
                continue;
            }
            $this->free($result);
            return TRUE;
        }
        $this->free($result);
        return FALSE;
    }

    public function free($res)
    {
        return mysql_free_result($res);
    }

    public function logsql($sql)
    {
        return;
        if (eregi("^insert into bet", $sql) || eregi("^delete from bet", $sql))
        {
            $sql = htmlspecialchars($sql, ENT_QUOTES);
            $this->query("insert into dblog (logs) values ('{$sql}')");
        }
        else
        {
            
        }
    }

}

class RecordSet
{

    public $result = false;
    public $eof = true;
    public $f = array();
    public $db;
    public $page = 0;
    public $pagesize = 20;
    public $currpos = 0;
    public $totalrecords = 0;
    public $totalpages = 0;

    public function RecordSet()
    {
        global $CORE;
        if (!isset($CORE['db']))
        {
            $CORE['db'] = new DB();
        }
        $this->db = $CORE['db'];
    }
	public function query($sql)
	{
		return $this->db->query($sql);	
	}
    public function open($sql, $page = 0, $pagesize = 20)
    {
        $this->page = $page;
        $this->pagesize = $pagesize;
        $this->result = $this->db->query($sql);
        if ($this->result == false)
        {
            $this->eof = true;
        }
        else if ($this->page != 0)
        {
            $c = ( $this->page - 1 ) * $this->pagesize;
            $this->db->data_seek($this->result, $c);
            $this->totalrecords = $this->db->num_rows($this->result);
            $this->totalpages = ceil($this->totalrecords / $this->pagesize);
            $this->f = $this->db->fetch_array($this->result);
            $this->eof = $this->f == false;
        }
        else
        {
            $this->f = $this->db->fetch_array($this->result);
            $this->eof = $this->f == false;
        }
        $this->currpos = 0;
    }

    public function movenext()
    {
        $this->next();
    }

    public function next()
    {
        if ($this->result == false)
        {
            $this->eof = true;
        }
        else
        {
            $this->f = $this->db->fetch_array($this->result);
            $this->eof = !$this->f;
            if (!$this->eof && $this->page != 0 && $this->pagesize <= ++$this->currpos)
            {
                $this->eof = true;
            }
        }
    }

    public function close()
    {
        if ($this->result)
        {
            $this->db->free_result($this->result);
        }
        $this->result = false;
        $this->eof = false;
        $this->f = array();
    }

    public function num_rows()
    {
        return $this->db->num_rows($this->result);
    }

    public function move($count)
    {
        $i = 0;
        while ($i < $count)
        {
            $this->movenext();
            ++$i;
        }
    }

    public function pagelink($noPage = TRUE)
    {
        $r = "<div id='y_pg'>";
        $url = $_SERVER['REQUEST_URI'];
        $url = preg_replace("/[\\?\\&]page=(\\d+)?/", "", $url);
        if ($noPage)
        {
            if (1 < $this->page)
            {
                $r .= "<a href='" . $url . "'>" . L_FIRSTPAGE . "</a>";
                $r .= "<a href='" . $url . "&page=" . ( $this->page - 1 ) . "'>" . L_PREVPAGE . "</a>";
            }
            else
            {
                $r .= "<span>" . L_FIRSTPAGE . "</span><span>" . L_PREVPAGE . "</span>";
            }
            if ($this->page < $this->totalpages)
            {
                $r .= "<a href='" . $url . "&page=" . ( $this->page + 1 ) . "'>" . L_NEXTPAGE . "</a>";
                $r .= "<a href='" . $url . "&page=" . $this->totalpages . "'>" . L_LASTPAGE . "</a>";
            }
            else
            {
                $r .= "<span>" . L_NEXTPAGE . "</span><span>" . L_LASTPAGE . "</span>";
            }
        }
        $r .= "<span>" . L_PAGE . " <select onchange=\"location.href='" . $url . "&page=' + this.value\">";
        $i = 1;
        while ($i <= $this->totalpages)
        {
            $r .= "<option value=" . $i;
            if ($this->page == $i)
            {
                $r .= " selected";
            }
            $r .= ">" . $i;
            ++$i;
        }
        $r .= "</select>";
        $r .= "，总共 " . $this->totalpages . " 页，" . $this->totalrecords . " 笔</span>";
        $r .= "</div>";
        return $r;
    }

}

function getrs($sql)
{
    global $CORE;
    if (!isset($CORE['db']))
    {
        $CORE['db'] = new DB();
    }
    return $CORE['db']->getrs($sql);
}

function getdb($sql, $page = 0, $pagesize = 20)
{
    $rs = new RecordSet();
    $rs->open($sql, $page, $pagesize);
    return $rs;
}

function db_IsExistsField($table, $field)
{
    $result = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field='" . $field . "'");
    if (!$result)
    {
        return false;
    }
    $chk = mysql_num_rows($result);
    mysql_free_result($result);
    return $chk;
}

function db_update($table, $fields, $where = "")
{
    global $CORE;
    if (!isset($CORE['db']))
    {
        $CORE['db'] = new DB();
    }
    $sql = "UPDATE {$table} SET ";
    foreach ($fields as $key => $val)
    {
        $sql .= $key . " = " . $val . ",";
    }
    if (substr($sql, 0 - 1) == ",")
    {
        $sql = substr($sql, 0, strlen($sql) - 1);
    }
    if ($where != "")
    {
        $sql .= " WHERE " . $where;
    }
    $CORE['db']->query($sql);
}
function dbquery($sql)
{
	global $CORE;
    if (!isset($CORE['db']))
    {
        $CORE['db'] = new DB();
    }
    return $CORE['db']->query($sql);	
}
function db_insert($table, $fields)
{
    global $CORE;
    if (!isset($CORE['db']))
    {
        $CORE['db'] = new DB();
    }
    $sql = "INSERT INTO {$table} (";
    $sql .= implode(",", array_keys($fields));
    $sql .= ") VALUES (";
    $sql .= implode(",", array_values($fields));
    $sql .= ")";

    if ($CORE['db']->query($sql))
    {
		$newid=mysql_insert_id($CORE['db']->handle_master);
		if(substr($table,0,3)=='bet')
		{
			$sql='update k_user set balance=balance-'.$fields['amount'].' where id='.$fields['user_id'];
			$CORE['db']->query($sql);
		}
        return $newid;
    }
    return false;
}

function db_insert_onduplicate($table, $fields, $updFileds)
{
    global $CORE;
    if (!isset($CORE['db']))
    {
        $CORE['db'] = new DB();
    }
    $sql = "INSERT INTO {$table} (";
    $sql .= implode(",", array_keys($fields));
    $sql .= ") VALUES (";
    $sql .= implode(",", array_values($fields));
    $sql .= ") ON DUPLICATE KEY UPDATE ";
    $cc = 0;
    foreach ($updFileds as $key => $vale)
    {
        $sql .= 0 < $cc ? "," : "";
        $sql .= "`{$key}` = `{$key}` + {$vale}";
        ++$cc;
    }
    if ($CORE['db']->query($sql))
    {
        return mysql_insert_id($CORE['db']->handle_master);
    }
    return false;
}

function sqlstr($str)
{
    if (!get_magic_quotes_gpc())
    {
        $str = addslashes($str);
    }
    return "'" . $str . "'";
}

$G_DB_QUERY_COUNT = 0;
?>